#!/usr/bin/env python3
"""
跨平台打包脚本
支持根据当前操作系统打包对应平台的应用程序
提供交互式界面让用户选择架构和打包格式
"""

import sys
import platform
import shutil
from pathlib import Path

# 项目根目录
PROJECT_ROOT = Path(__file__).parent.parent
SRC_DIR = PROJECT_ROOT / "src"
RESOURCES_DIR = PROJECT_ROOT / "resources"
BUILD_DIR = PROJECT_ROOT / "build"
DIST_DIR = PROJECT_ROOT / "dist"

def load_project_config():
    """从pyproject.toml加载项目配置"""
    try:
        import tomllib  # Python 3.11+
    except ImportError:
        import tomli as tomllib  # Python 3.10及以下
    
    project_root = Path(__file__).parent.parent
    pyproject_path = project_root / "pyproject.toml"
    
    with open(pyproject_path, 'rb') as f:
        config = tomllib.load(f)
    
    project = config['project']
    return {
        "name": project['name'],
        "version": project['version'],
        "description": project['description'],
        "author": project['authors'][0]['name'] if project.get('authors') else "Unknown",
        "main_script": "main.py"
    }

# 从配置文件加载
DEFAULT_CONFIG = load_project_config()

class BuildConfig:
    """打包配置类"""
    
    def __init__(self):
        self.current_platform = platform.system().lower()
        self.current_arch = platform.machine().lower()
        self.target_platform = self.current_platform
        self.target_arch = self._normalize_arch(self.current_arch)
        self.build_type = "app"  # app 或 installer
        self.clean_build = True
        self.one_file = True
        self.windowed = True
    
    def _normalize_arch(self, arch):
        """标准化架构名称"""
        arch_map = {
            "amd64": "x64",
            "x86_64": "x64",
            "i386": "x86",
            "i686": "x86",
            "arm64": "arm64",
            "aarch64": "arm64"
        }
        return arch_map.get(arch.lower(), arch.lower())
    
    def validate(self):
        """验证配置是否有效"""
        if self.target_platform != self.current_platform:
            print(f"警告：当前只能为 {self.current_platform} 平台打包")
            self.target_platform = self.current_platform
            return False
        return True

class InteractiveBuilder:
    """交互式打包器"""
    
    def __init__(self):
        self.config = BuildConfig()
    
    def run(self):
        """运行交互式打包流程"""
        print("=== 色块图片下载器 - 打包工具 ===")
        print(f"当前平台: {platform.system()} {platform.machine()}")
        print()
        
        # 显示当前配置
        self._show_current_config()
        
        # 用户选择
        if not self._get_user_choice():
            print("打包已取消")
            return
            
        # 执行打包
        self._build()
    
    def _show_current_config(self):
        """显示当前配置"""
        print("当前配置:")
        print(f"  目标架构: {self.config.target_arch}")
        print(f"  打包类型: {'应用程序' if self.config.build_type == 'app' else '安装包'}")
        print(f"  单文件模式: {'是' if self.config.one_file else '否'}")
        print()
    
    def _get_user_choice(self):
        """获取用户选择"""
        try:
            # 显示退出提示
            print("提示: 输入 'q' 或 'quit' 随时退出")
            
            # 选择架构
            print("选择目标架构:")
            print(f"1. x64 (64位) {'(当前架构)' if self.config.target_arch == 'x64' else ''}")
            print(f"2. x86 (32位) {'(当前架构)' if self.config.target_arch == 'x86' else ''}")
            print(f"3. arm64 (ARM64) {'(当前架构)' if self.config.target_arch == 'arm64' else ''}")
            
            arch_choice = input("请输入选择 [1-3] (默认: 当前架构): ").strip().lower()
            if arch_choice in ['q', 'quit']:
                return False
            elif arch_choice == "1":
                self.config.target_arch = "x64"
            elif arch_choice == "2":
                self.config.target_arch = "x86"
            elif arch_choice == "3":
                self.config.target_arch = "arm64"
            
            # 选择打包类型
            print("\n选择打包类型:")
            print("1. 应用程序 (可直接运行)")
            print("2. 安装包 (包含安装程序)")
            
            type_choice = input("请输入选择 [1-2] (默认: 1): ").strip().lower()
            if type_choice in ['q', 'quit']:
                return False
            elif type_choice == "2":
                self.config.build_type = "installer"
            
            # 其他选项
            one_file_choice = input("\n是否使用单文件模式? [y/N] (默认: 是): ").strip().lower()
            if one_file_choice in ['q', 'quit']:
                return False
            elif one_file_choice == "n":
                self.config.one_file = False
            
            clean_choice = input("是否清理之前的构建文件? [y/N] (默认: 是): ").strip().lower()
            if clean_choice in ['q', 'quit']:
                return False
            elif clean_choice == "n":
                self.config.clean_build = False
            
            return True
            
        except KeyboardInterrupt:
            print("\n\n打包已取消")
            return False
    
    def _build(self):
        """执行打包"""
        print("\n开始打包...")
        
        # 验证配置
        if not self.config.validate():
            return
        
        # 清理构建目录
        if self.config.clean_build:
            self._clean_build_dirs()
        
        # 根据平台选择打包方式
        if self.config.target_platform == "windows":
            self._build_windows()
        elif self.config.target_platform == "darwin":
            self._build_macos()
        elif self.config.target_platform == "linux":
            self._build_linux()
        else:
            print(f"不支持的平台: {self.config.target_platform}")
            return
    
    def _clean_build_dirs(self):
        """清理构建目录"""
        print("清理构建目录...")
        for dir_path in [BUILD_DIR, DIST_DIR]:
            if dir_path.exists():
                shutil.rmtree(dir_path)
                dir_path.mkdir(exist_ok=True)
    
    def _build(self):
        """执行打包"""
        print("\n开始打包...")
        
        # 验证配置
        if not self.config.validate():
            return
        
        # 清理构建目录
        if self.config.clean_build:
            self._clean_build_dirs()
        
        # 根据平台选择打包方式
        if self.config.target_platform == "windows":
            from windows_builder import build_windows_package
            build_windows_package(DEFAULT_CONFIG["name"], DEFAULT_CONFIG["main_script"], self.config)
        elif self.config.target_platform == "darwin":
            from macos_builder import build_macos_package
            build_macos_package(DEFAULT_CONFIG["name"], DEFAULT_CONFIG["main_script"], self.config)
        elif self.config.target_platform == "linux":
            from linux_builder import build_linux_package
            build_linux_package(DEFAULT_CONFIG["name"], DEFAULT_CONFIG["main_script"], self.config)
        else:
            print(f"不支持的平台: {self.config.target_platform}")

def main():
    """主函数"""
    # 检查PyInstaller是否安装
    try:
        import PyInstaller
    except ImportError:
        print("错误: PyInstaller未安装")
        print("请运行: pip install pyinstaller")
        return 1
    
    builder = InteractiveBuilder()
    builder.run()
    return 0

if __name__ == "__main__":
    sys.exit(main())